using System.Collections.Generic;
using server.Models;
using System.Text.Json;
namespace server.Services;

public class TokenService
{
    public Dictionary<int, UserToken> TokenCache { get; set; } = new Dictionary<int, UserToken>();
    public UserToken GetOrCreateToken(User user)
    {
        CleanOutdated();
        UserToken token;
        if (TokenCache.ContainsKey(user.ID))
        {
            token = TokenCache[user.ID];
            if (!token.IsOutdated())
            {
                System.Console.WriteLine("Find valid token:",token.ID);
                return token;
            }
            else
            {
                System.Console.WriteLine("Find valid token:",token.ID);
                TokenCache.Remove(user.ID);
            }
        }
        token = new UserToken(user);
        TokenCache.Add(user.ID, token);
        System.Console.WriteLine("Create New token:",JsonSerializer.Serialize(token));
        return token;
    }

    public bool ValidateToken(int uid, long token_id, Right right)
    {
        if (!TokenCache.ContainsKey(uid))
        {
            return false;
        }
        var token=TokenCache[uid];
        if (token.ID!=token_id)
        {
            return false;
        }
        if(token.IsOutdated()){
            TokenCache.Remove(uid);
            return false;
        }
        return (token.Right & right) == right;
    }

    public void CleanOutdated()
    {
        var outdated_keys = new List<int>();
        foreach (var entry in TokenCache)
        {
            if (entry.Value.IsOutdated())
            {
                outdated_keys.Add(entry.Key);
            }
        }
        outdated_keys.ForEach(k =>
        {
            TokenCache.Remove(k);
            System.Console.WriteLine("Remove outdated token:"+k);
        });
    }
}